package service;

import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.assist.Network;
import com.example.menhoo.toollibrary.common.helper.AndroidFileUtil;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.cache.MD5FileNameGenerator;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.http.client.multipart.MultipartEntity;
import com.lidroid.xutils.util.LogUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import application.UIApplication;
import application.UIHttpURL;
import application.UIKeyValueSet;
import model.DownloadDbModel;
import receiver.DownloadAddQueueReceiver;
import receiver.DownloadCancelledReceiver;
import receiver.DownloadErrorReceiver;
import receiver.DownloadFinishReceiver;
import receiver.DownloadLoadingReceiver;
import receiver.DownloadStartReceiver;
import receiver.UploadCancelledReceiver;
import receiver.UploadErrorReceiver;
import receiver.UploadFinishReceiver;
import receiver.UploadLoadingReceiver;
import receiver.UploadStartReceiver;

/**
 * 这是一个下载服务,需要注意的是要在程序启动的时候,把所以未完成的下载任务设置为stop,避免app自动下载,上一次未完成的任务
 * Created by yanglei on 15/9/26.
 */
public class DownLoadService extends UIService {

    public static String ONLY_WIFI_DOWNLOAD="ONLY_WIFI_DOWNLOAD";

    class DownFileInfo{
        public String fileName;
        public int fileSize;
    }

    private static Map<String,HttpHandler> downloadList=new HashMap();
    IBinder binder=new DownLoadBinder();

    /**
     * 得到当前正在下载的任务
     * @return
     */
    public List<DownloadDbModel> getCurrDownloadingItem(){
        try {
            List<DownloadDbModel> list = getDB().findAll(Selector.from(DownloadDbModel.class).where("status", "=", "start").orderBy("updateTime", false));
            if(list!=null && list.size()>0){
                return list;
            }

        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }
        return null;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class DownLoadBinder extends Binder{
        public DownLoadService getService(){
            return DownLoadService.this;
        }
    }

    private void showInfo(String infoText){
//        try{
//            MessageUtil.showSingletonToast(getApplicationContext(), infoText);
//        }
//        catch (Exception e){
//            LogUtils.e(e.getMessage()+"");
//        }
    }

    /**
     * 停止所有任务,但不清除
     */
    public static void stopAllDownloadTask(DbUtils db){
        try {
            List<DownloadDbModel> list = db.findAll(Selector.from(DownloadDbModel.class).where("status","=","start"));
            if(list!=null && list.size()>0){
                for(DownloadDbModel item :list){
                    item.status="stop";
                    if(downloadList!=null && downloadList.containsKey(item.url)){
                        HttpHandler httpHandler=downloadList.get(item.url);
                        if(httpHandler!=null){
                            httpHandler.cancel();
                        }
                        downloadList.remove(item.url);
                    }
                }
                db.updateAll(list);
            }
            LogUtils.e("停止所有任务-成功");
        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }
    }

    /**
     * 根据url得到要下载文件的,文件名
     * @param url
     * @return
     */
    public DownFileInfo getDownloadFileName(String url){
        String file_name=null;
        try {
            URL myURL = new URL(url);
            URLConnection conn = myURL.openConnection();
            file_name = conn.getHeaderField("Content-Disposition");
            if(!Check.isEmpty(file_name)){
                file_name=new String(file_name.getBytes("ISO-8859-1"), "GBK");
                int location = file_name.indexOf("filename");
                if (location >= 0) {
                    file_name = file_name.substring(location
                            + "filename".length());
                    file_name = file_name
                            .substring(file_name.indexOf("=") + 1).replace("\"","");

                }
                else{
                    file_name = URLDecoder.decode(url, "UTF-8");
                    //说明服务器没有提供名字,看看能否通过url来得到名字
                    String newUrl = url;
                    int len = url.indexOf("?");
                    if(len>=0){
                        newUrl = url.substring(0, len);//去掉参数
                    }
                    String endName=newUrl.substring(newUrl.lastIndexOf("/") + 1,newUrl.length());
                    String firstName = file_name.substring(0, file_name.lastIndexOf("/") + 1);
                    file_name=firstName+endName;
                }
            }
            else{

                //说明服务器没有提供名字,看看能否通过url来得到名字
                String newUrl = url;
                int len = url.indexOf("?");
                if(len>=0){
                    newUrl = url.substring(0, len);//去掉参数
                }
                String endName=newUrl.substring(newUrl.lastIndexOf("/") + 1,newUrl.length());

                file_name=endName;

            }
            if(Check.isEmpty(file_name)){
                file_name=new MD5FileNameGenerator().generate(url);
            }
            file_name = URLDecoder.decode(file_name, "UTF-8");

            //看看是否有同名文件,如果有,则新获得的文件添加序号 (1),(2),(3),(...)
            try {
                long file_name_count =getDB().count(Selector.from(DownloadDbModel.class).where("name","=",file_name));
                if(file_name_count>0){

                    String suffix= AndroidFileUtil.getSuffix(file_name);
                    String fileName=Check.isEmpty(suffix)?file_name:file_name.replace("."+suffix,"");
                    String customChar = " (__)";
                    long file_name_superCount = getDB().count(Selector.from(DownloadDbModel.class).where("name","like",fileName+customChar+"."+suffix));
                    if(file_name_superCount>99){
                        Date date = new Date();
                        file_name=fileName+"_"+date.getTime()+"."+suffix;
                    }
                    else if(file_name_superCount>0 && file_name_superCount<100){
                        file_name = fileName+customChar.replace("__",String.format("%02d",file_name_superCount+1))+"."+suffix;
                    }
                    else{
                        file_name = fileName+customChar.replace("__",String.format("%02d",1))+"."+suffix;
                    }
                }
            }catch (Exception e){

            }

            LogUtils.i("得到下载文件的文件名:"+file_name+";大小:"+conn.getContentLength());
            DownFileInfo dfi = new DownFileInfo();
            dfi.fileName=file_name;
            dfi.fileSize=conn.getContentLength();
            return dfi;
        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }
        return null;
    }
    /**
     * 加入到下载队列
     * @param tag 下载文件的唯一标识
     * @param url
     * @param saveFilePath
     */
    public void addDownloadQueue(final String tag, final String url, final String saveFilePath){

        //1看看是否有网络
        boolean isNetwork = Network.isConnected(getApplicationContext());
        if(isNetwork){
            //2先取得要下载的文件名称
            //3加入到下载队列里好等待下载
            try {
                Thread.sleep(100);
            }
            catch (Exception e){}
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        //先判断是否只允许wifi下载
                        String isWifi = UIApplication.getAppKeyValueSet().readAppSetPreferences(UIKeyValueSet.IsOnlyWiFiUploadAndDownload);
                        if(isWifi!=null && isWifi.equals("true")){
                            if(!Network.isWifi(getApplicationContext())){
                                //不是wifi的话就退出
                                Intent it = new Intent();// 创建Intent对象
                                it.setAction(DownloadErrorReceiver.Action);
                                it.putExtra("url", url);
                                it.putExtra("tag", tag);
                                it.putExtra("msg", "ONLY_WIFI_DOWNLOAD");
                                sendBroadcast(it);
//                                showInfo("只允许wifi下载");
                                return;
                            }
                        }

                        DownFileInfo dfi =getDownloadFileName(checkURL(url));

                        DownloadDbModel downDB = getDB().findFirst(Selector.from(DownloadDbModel.class).where("tag","=",tag).or("url","=",url));
                        if(downDB!=null){
                            //如果数据存在
                            if(downDB.isComplete){
                                Intent it = new Intent();// 创建Intent对象
                                it.setAction(DownloadErrorReceiver.Action);
                                it.putExtra("url", url);
                                it.putExtra("tag", tag);
                                it.putExtra("msg", "文件已经存在");
                                LogUtils.e("文件已经存在");
                                sendBroadcast(it);
                                showInfo("文件已经存在");
                            }
                            else{
                                downDB.status="start";
//                                downDB.url=url;
                                downDB.updateTime = new Date();
                                getDB().update(downDB);
                                executeOneDownload();
                                showInfo("文件已在下载队列中,即将开始下载...");
                            }
                        }
                        else{
                            DownloadDbModel downloadDbModel = new DownloadDbModel();
                            downloadDbModel.tag = tag;
                            downloadDbModel.url = url;
                            downloadDbModel.path = saveFilePath;
                            downloadDbModel.name = dfi.fileName;
                            downloadDbModel.isComplete=false;
                            downloadDbModel.size = dfi.fileSize;
                            downloadDbModel.status="start";
                            getDB().save(downloadDbModel);
                            executeOneDownload();

                            Intent it = new Intent();// 创建Intent对象
                            it.setAction(DownloadAddQueueReceiver.Action);
                            it.putExtra("url", url);
                            it.putExtra("tag", tag);
                            it.putExtra("fileName", dfi.fileName);
                            it.putExtra("fileSize", dfi.fileSize);
                            sendBroadcast(it);
                            showInfo("文件已添加到下载队列...");
                        }
                    }
                    catch (Exception e){
                        LogUtils.e(e.getMessage() + "");
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadErrorReceiver.Action);
                        it.putExtra("url", url);
                        it.putExtra("tag", tag);
                        it.putExtra("msg", "获得不到名字");
                        sendBroadcast(it);
                    }
                }
            }).start();
        }
        else{
            LogUtils.d("addDownloadQueue下载错误:没有网络");
            Intent it = new Intent();// 创建Intent对象
            it.setAction(DownloadErrorReceiver.Action);
            it.putExtra("url", url);
            it.putExtra("tag", tag);
            it.putExtra("msg", "无网络");
            sendBroadcast(it);
        }

    }
    /**
     * 下载 需要调用 setDownLoadReceiverHandle(IDownLoadListener)
     * @param tag 可选的一个string类型参数,会和广播一起返回,一般根据它来判断正在更新的是哪一条数据
     * @param file_name 文件真实名称
     * @param url
     * @param saveFilePath 要下载到的目录(你要下载到哪里)
     */
    public void download(String tag,String file_name, final String url,String saveFilePath){
        final String Tag= tag;
        final String SaveFilePathF=saveFilePath;
        final String urlF = url;

        final String fileNameF=file_name;
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__",UIApplication.getSession()!=null?UIApplication.getSession():"");
        HttpHandler<File> handler = http.download(urlF,
                SaveFilePathF,
                params,
                true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        setRate(200);
                        LogUtils.d("开始下载:");
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadStartReceiver.Action);
                        it.putExtra("url", urlF);
                        it.putExtra("tag", Tag);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        LogUtils.d("当前下载:" + current + "/" + total);
                        //发送群组更新广播
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadLoadingReceiver.Action);
                        it.putExtra("url", urlF);
                        it.putExtra("tag", Tag);
                        it.putExtra("total", total);
                        it.putExtra("current", current);
                        sendBroadcast(it);

                        try {
                            DownloadDbModel downloadDbModel = getDB().findFirst(Selector.from(DownloadDbModel.class).where
                                    ("url", "==", urlF));
                            if (downloadDbModel != null) {
                                downloadDbModel.currDownloadSize = current;
                                getDB().update(downloadDbModel);
                            }

                        } catch (Exception e) {
                            LogUtils.e(e.getMessage() + "");
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {

                        LogUtils.d("下载成功:" + responseInfo.result.getPath());
                        try {
                            String decodePath = URLDecoder.decode(responseInfo.result.getPath(), "UTF-8");
                            if (decodePath.indexOf(".temp") >= 0) {
                                //说明服务器没有提供名字,看看能否通过url来得到名字
                                String firstName = decodePath.substring(0, decodePath.lastIndexOf("/") + 1);
                                decodePath = firstName + fileNameF;
                            }
                            File newFile = new File(decodePath);
                            responseInfo.result.renameTo(newFile);
                            //更新数据库

                            DownloadDbModel downloadDbModel = getDB().findFirst(Selector.from(DownloadDbModel.class).where
                                    ("url", "==", urlF));
                            if (downloadDbModel != null) {
                                downloadDbModel.tag = Tag;
                                downloadDbModel.path = decodePath;
                                downloadDbModel.name = newFile.getName();
                                downloadDbModel.currDownloadSize = newFile.length();
                                downloadDbModel.size = newFile.length();
                                downloadDbModel.createTime = new Date();
                                downloadDbModel.isComplete = true;
                                downloadDbModel.status = "complete";
                                getDB().update(downloadDbModel);
                                DownloadDbModel downloadDbModels = getDB().findFirst(Selector.from(DownloadDbModel.class).where
                                        ("url", "==", urlF));
                                if (downloadDbModels==null){
                                    LogUtils.e("更新缓存：downloadDbModels==null");
                                }else {
                                    LogUtils.e("更新缓存：downloadDbModels！=null");
                                }
                                LogUtils.d("下载:更新数据 url:" + urlF);
                            } else {
                                downloadDbModel = new DownloadDbModel();
                                downloadDbModel.tag = Tag;
                                downloadDbModel.url = urlF;
                                downloadDbModel.path = decodePath;
                                downloadDbModel.name = newFile.getName();
                                downloadDbModel.currDownloadSize = newFile.length();
                                downloadDbModel.size = newFile.length();
                                downloadDbModel.isComplete = true;
                                downloadDbModel.status = "complete";
                                getDB().save(downloadDbModel);
                                LogUtils.d("下载:添加数据(正常不该出现) url:" + urlF);
                            }

                            Intent it = new Intent();// 创建Intent对象
                            it.setAction(DownloadFinishReceiver.Action);
                            it.putExtra("url", urlF);
                            it.putExtra("tag", Tag);
                            it.putExtra("filePath", decodePath);
                            sendBroadcast(it);
                            showInfo("[" + newFile.getName() + "] 已下载成功");
                            //清除
                            cancelDownload(urlF);
                            executeOneDownload();

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            LogUtils.e(e.getMessage() + "");
                        } catch (DbException e) {
                            e.printStackTrace();
                            LogUtils.e(e.getMessage() + "");
                        }

                    }

                    @Override
                    public void onCancelled() {
                        LogUtils.d("下载取消了:" + urlF);
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadCancelledReceiver.Action);
                        it.putExtra("url", urlF);
                        it.putExtra("tag", Tag);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        LogUtils.d("下载错误:" + msg);
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadErrorReceiver.Action);
                        it.putExtra("url", urlF);
                        it.putExtra("tag", Tag);
                        it.putExtra("msg", "无法下载...");
                        sendBroadcast(it);

                        //清除
                        cancelDownload(urlF);
                        executeOneDownload();
                    }
                });

        downloadList.put(urlF, handler);
    }

    /**
     * 根据下载地址,清除下载
     * @param url 下载地址
     */
    public void cancelDownload(String url){
        try {
            DownloadDbModel downDB = getDB().findFirst(Selector.from(DownloadDbModel.class).where
                    ("url", "=", url));
            if(downDB!=null){
                downDB.status="stop";
                getDB().update(downDB);
            }
            if(downloadList!=null && downloadList.containsKey(url)){
                HttpHandler httpHandler=downloadList.get(url);
                downloadList.remove(url);
                if(httpHandler!=null){
                    httpHandler.cancel();
                }
            }
            LogUtils.i("执行取消任务:"+url);
            executeOneDownload();
        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }

    }

    /**
     * 执行一个下载任务,如果有的话
     */
    public void executeOneDownload(){

        try {
            //看看现在有无下载任务
            if(downloadList.size()>0){
                LogUtils.i("当前有下载任务");
                return;
            }
            //在数据库中找到一个符合条件的可下载的任务
            DownloadDbModel item = getDB().findFirst(Selector.from(DownloadDbModel.class).where("status", "=", "start").and
                    ("isComplete", "=", false).orderBy("updateTime",false));
            if(item!=null){
                download(item.tag,item.name,item.url,item.path);
                LogUtils.i("开始下载新任务:"+item.name);
            }

        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }
    }
    /**
     * 上传 需要调用 setUploadLoadReceiverHandle(IUpLoadListener)
     * @param tag 可选的一个string类型参数,会和广播一起返回,一般根据它来判断正在更新的是哪一条数据
     * @param url
     * @param sd_file_name 要上传的完整文件名[包括文件夹+'/'+文件名]
     */
    public void upload(String tag,String url,String sd_file_name){
        // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
        // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
        // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
        // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
        // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));

        final String Tag = tag;
        final String URL = url;
        final String SD_FILE_NAME = sd_file_name;
        RequestParams params = new RequestParams();
        //FileUploadEntity entity =new FileUploadEntity(new File(sd_file_name),"application/octet-stream");
        MultipartEntity ee = new MultipartEntity();
        //params.setBodyEntity(entity);

//        ee.setMultipartSubtype("related");
//        params.setBodyEntity(ee);
        params.addBodyParameter("file", new File(sd_file_name));
        HttpUtils http = new HttpUtils();
        http.send(HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        setRate(200);
                        LogUtils.d("开始上传:");
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadStartReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            LogUtils.d("当前上传: " + current + "/" + total);
                            //发送群组更新广播
                            Intent it = new Intent();// 创建Intent对象
                            it.setAction(UploadLoadingReceiver.Action);
                            it.putExtra("url", URL);
                            it.putExtra("tag", Tag);
                            it.putExtra("total", total);
                            it.putExtra("current", current);
                            sendBroadcast(it);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        LogUtils.d("上传成功:" + responseInfo.result);
                        //
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadFinishReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        it.putExtra("filePath", SD_FILE_NAME);
                        it.putExtra("webResult", responseInfo.result);
                        sendBroadcast(it);

                    }

                    @Override
                    public void onCancelled() {
                        LogUtils.d("上传取消了:" + SD_FILE_NAME);
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadCancelledReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        LogUtils.d("上传错误:"+msg);
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadErrorReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        it.putExtra("msg", msg);
                        sendBroadcast(it);
                    }
                });
    }

    /**
     * 上传 需要调用 setUploadLoadReceiverHandle(IUpLoadListener)
     * @param tag 可选的一个string类型参数,会和广播一起返回,一般根据它来判断正在更新的是哪一条数据
     * @param url
     * @param sd_file_name 要上传的完整文件名[包括文件夹+'/'+文件名]
     */
    public HttpHandler<String> uploadHaveparamsAndRetHandler(String tag,String url,String sd_file_name,String paramsStr,int sort){
        // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
        // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
        // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
        // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
        // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));

        final String Tag = tag;

        final String URL = url;

        final String SD_FILE_NAME = sd_file_name;

        RequestParams params = new RequestParams();
        params.addBodyParameter("file", new File(sd_file_name));

        try {
            JSONArray ja = new JSONArray(paramsStr);
            for(int j = 0; j < ja.length(); j++){
                JSONObject jp = ja.getJSONObject(j);
                params.addBodyParameter(jp.getString("key"),jp.getString("value"));

                LogUtils.d(jp.getString("key")+":"+jp.getString("value"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.addBodyParameter("sort", "" + sort);
        LogUtils.d("sort:"+sort);
        HttpUtils http = new HttpUtils();
        HttpHandler<String> h = http.send(HttpMethod.POST,
                url,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        setRate(200);
                        LogUtils.d("开始上传:" + Tag);
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadStartReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            LogUtils.d("当前上传: " + current + "/" + total);
                            //发送群组更新广播
                            Intent it = new Intent();// 创建Intent对象
                            it.setAction(UploadLoadingReceiver.Action);
                            it.putExtra("url", URL);
                            it.putExtra("tag", Tag);
                            it.putExtra("total", total);
                            it.putExtra("current", current);
                            sendBroadcast(it);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        LogUtils.d("上传成功:"+Tag+";" + responseInfo.result);
                        //
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadFinishReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        it.putExtra("filePath", SD_FILE_NAME);
                        it.putExtra("webResult", responseInfo.result);
                        sendBroadcast(it);

                    }

                    @Override
                    public void onCancelled() {
                        LogUtils.d("上传取消了:" + SD_FILE_NAME);
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadCancelledReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        LogUtils.d("上传错误:" + msg);
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(UploadErrorReceiver.Action);
                        it.putExtra("url", URL);
                        it.putExtra("tag", Tag);
                        it.putExtra("msg", msg);
                        sendBroadcast(it);
                    }
                });
        return h;
    }


    /**
     * 加工url 相对路径加http+网站,没有session的家__session__
     */
    String checkURL(String url) {
        if (Check.isEmpty(url)) {
            return null;
        }
        String fullURL = UIHttpURL.getWebSiteFullUrl(url);
        Map<String, String> parameters = UIHttpURL.getUrlParameters(fullURL);
        if (parameters==null || !parameters.containsKey("__session__")) {
            Map<String, String> map = new HashMap();
            map.put("__session__", UIApplication.getSession());
            return UIHttpURL.getWebSiteFullUrl(url, map);
        }
        return fullURL;
    }
}
